var VNCBase64Renderer = Class.create({
	dimensions: null,
	
	initialize: function(container,parent,proxy) {
		this.container = container;
		this.elements = [];
		this.parent = parent;
		this.proxy = proxy;
		var scope = this;
		
	},

	
	recvUpdate: function(data) {

		if (!this.proxy) {
			this.checkOverlapped(data.x, data.y, data.width, data.height);
			this.createDOM(data.x, data.y, data.width, data.height, data.data);
		
			this.renderRectangles();
		} else {
			var img = this.paintImg(data.width, data.height, data.data);
			var scope = this;
			img.onload = function(){
				scope.proxy.renderImg(img, data.x, data.y);
			}
		}
	},
	
	paintImg: function(w,h,data) {
		var img = new Image();
		img.src = "data:image/png;base64,"+data;
		return img;
	},
		
	renderRectangles: function() {
		var elem;
		var spliceList = [];
		for(i=0;i<this.elements.length; i++) {
			elem = this.elements[i];	
			if(!elem)
				continue;
			if(!elem.rendered && !elem.deleteMe) {
				this.parent.targetDOM.appendChild(elem.DOM)
				elem.rendered = true;
			}
			if(elem.deleteMe) {
				if(elem.DOM) {
					if(elem.DOM.parentNode == this.parent.targetDOM) {
						this.parent.targetDOM.removeChild(elem.DOM)
						spliceList.push(i);
					}
				}
			}
		}
		while(spliceList.length) {
			this.elements.splice(spliceList.pop(),1);
		}
	},
	
	checkOverlapped: function(x,y,w,h) {
		var cur,s_br = x+w,s_bb = y+h;
		for(var i=0;i<this.elements.length;i++) {
			cur = this.elements[i];
			if(!cur || cur.deleteMe)
				continue;
			// no overlap 
			if(cur.br < x || cur.bb < y || s_bb < cur.y || s_br < cur.x)
				continue;

			if(cur.x >= x && cur.br <= s_br && cur.y >= y && cur.bb <= s_bb) {
				
				cur.deleteMe = true;
			}
			if(cur.x < x && cur.br >= x && cur.br <= s_br)
				cur.br = x;
			if(cur.x >= x && cur.x <= s_br && cur.br >= s_br)
				cur.x = s_br;
			if(cur.y < y && cur.bb >= y && cur.bb <= s_bb)
				cur.br = x;
			if(cur.y >= y && cur.y <= s_bb && cur.bb >= s_bb)
				cur.y = s_bb;
			if(cur.rendered)
				if((cur.x == cur.br)|| (cur.y == cur.bb)) {
					cur.deleteMe = true;
				}
		};
		
	},
	
	createDOM : function(y,x,width,height,data) {
		var dom = {}
		dom.DOM = new Element("div", {		
			style : "position:absolute;width:"+width+"px;height:"+height+"px;left:"+y+"px;top:"+x+"px;"+
					";background-image:url(data:image/png;base64,"+data+")"
		});
		dom.x = x;
		dom.y = y;
		dom.width = width;
		dom.height = height;
		dom.br = x+width;
		dom.bb = y+height;
		dom.rendered = false;
		this.elements.push(dom);
	}
	

})
